const canvas = document.getElementById("canvas");
const ctx2d = canvas.getContext("2d");

const observer = new ResizeObserver((e) => {
  const { width, height } = e[0].contentRect;
  canvas.width = width;
  canvas.height = height;

  initCtx(ctx2d);
  drawAxis(ctx2d);
  draw(ctx2d);
});
observer.observe(document.body);
// observer.unobserve(document.body);
// observer.disconnect();

const initCtx = (ctx) => {
  if (ctx) {
    ctx.translate(canvas.width / 2, canvas.height / 2);
    ctx.scale(1, -1);
  }
};

const drawAxis = (ctx) => {
  if (ctx) {
    ctx.beginPath();
    ctx.strokeStyle = "#FfFfFf80";
    ctx.lineWidth = 1;
    ctx.moveTo(0, 0);
    ctx.lineTo(canvas.width / 2 - 10, 0);
    ctx.moveTo(0, 0);
    ctx.lineTo(0, canvas.height / 2 - 10);
    ctx.moveTo(0, 0);
    ctx.lineTo(-canvas.width / 2 + 10, 0);
    ctx.moveTo(0, 0);
    ctx.lineTo(0, -canvas.height / 2 + 10);
    ctx.stroke();
  }
};

const draw = (ctx) => {
  if (ctx) {
    ctx.beginPath();
    ctx.strokeStyle = "#FF000080";
    ctx.lineWidth = 1;
    const n = 40;
    const r = 300;
    let Alpha, Theta; //定义金刚石图案的起始角与等分角
    Theta = (2 * Math.PI) / n; //θ为等分角
    Alpha = Math.PI / 2 - Theta; //α为起始角,用于调整图案起始方位
    const P = [];
    for (
      let i = 0;
      i < n;
      i += 1 //计算等分点坐标
    ) {
      P.push({
        x: r * Math.cos(i * Theta + Alpha),
        y: r * Math.sin(i * Theta + Alpha),
      });
    }
    for (
      i = 0;
      i <= n - 2;
      i++ //依次各连接等分点
    ) {
      for (let j = i + 1; j <= n - 1; j += 1) {
        ctx.moveTo(Math.round(P[i].x), Math.round(P[i].y));
        ctx.lineTo(Math.round(P[j].x), Math.round(P[j].y));
      }
    }
    ctx.stroke();
  }
};
